package com.dayuanit.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dayuanit.dao.CarDao;
import com.dayuanit.dao.GoodDao;
import com.dayuanit.domain.Car;
import com.dayuanit.domain.Good;
import com.dayuanit.exception.MallBusException;
import com.dayuanit.service.CarService;

@Service
public class CarServiceImpl implements CarService {
	
	@Autowired
	private CarDao carDao;
	
	@Autowired
	private GoodDao goodDao;

	@Override
	public void addGood(int goodId, int userId) {
		
		Good good = goodDao.getGood(goodId);
		if (null == good) {
			throw new MallBusException("商品不存在");
		}
		
		if (good.getNum() <= 0) {
			throw new MallBusException("商品库存不够");
		}
		
		if (good.getStatus() != 1) {
			throw new MallBusException("商品未上架");
		}
		
		Car loadCar = carDao.getCarByGoodId(goodId, userId);
		if (null != loadCar) {
			throw new MallBusException("已添加");
		}
		
		Car car = new Car();
		car.setGoodId(goodId);
		car.setNum(1);
		car.setStatus(0);
		car.setUserId(userId);
		int rows = carDao.add(car);
		if (1 != rows) {
			throw new MallBusException("添加购物车失败");
		}
	}

	@Override
	public List<Car> listCar(int userId) {
		return carDao.listCar(userId);
	}

}
